import React, { Component } from 'react';
import { Spin,Row,Col,Icon,Skeleton  } from 'antd';
import Link  from 'next/link';
import Router from "next/router";
import { connect } from 'react-redux'
import * as API from '../../api/api'
import MyLayout from '../../components/layout';
import ArticleItem from '../../components/articleItem/index';
import { loadMore } from '../../utils/';
import config from '../../config'
import {storePage,storeHasMore,storeArticles,storeCategories} from '../../store/article/action'
import './index.less';


const LIMIT = config.articleLimit;
function mapStateToProps (state) {
    return {
        articles: state.article.articles,
        page:state.article.page,
        hasMore:state.article.hasMore,
    }
}
function mapDispatchToProps(dispatch) {
    return {
        storePage:  (page) => {dispatch(storePage(page))},
        storeHasMore: (hasMore) => {dispatch(storeHasMore(hasMore))},
        storeArticles: (articles) => {dispatch(storeArticles(articles))},
        storeCategories: (categories) => {dispatch(storeCategories(categories))},
    }
  }
  
@connect(mapStateToProps,mapDispatchToProps)
export default class Home extends Component{ 
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            activeTab:''
        };
    }

    static async getInitialProps ({req ,query,reduxStore}) {
        let {type} = query;
        let blogList = [];
        let {categories} = reduxStore.getState().article;
        let {dispatch} = reduxStore;
        let resBlog = await API.getArticleList({limit:LIMIT,page:1,type});
        blogList = resBlog.data.data;
        let hasMore = resBlog.data.hasMore;
        dispatch(storePage(1))
        dispatch(storeArticles(blogList))
        dispatch(storeHasMore(hasMore))   
        if(!categories.length){
            let resCt = await API.getCateAndTag();
            categories = resCt.data.categories;
            dispatch(storeCategories(categories))
        }
        return {blogList,categories,type}; 
    }
   
    componentDidUpdate(prevProps) {
        // const { pathname, query } = this.props.router
        // // verify props have changed to avoid an infinite loop
        // if (query.id !== prevProps.router.query.id) {
        //   // fetch data based on the new query
        // }
    }
    componentWillMount() {
     
    }
    componentDidMount(){
        window.addEventListener('scroll', this.loadMore);
    }
    getArticles() {
        let {page,type} = this.props;
        this.setState({
            loading:true
        })
        let params = {
            limit: LIMIT,
            page,
            categoryId:type,
        }
        API.getArticleList(params).then(res => {
            if (res.data.code === 1) {
                // if (res.data.data.length > 0) {
                let articles = res.data.data;
                let hasMore = res.data.hasMore;
                this.props.storePage(page);
                this.props.storeHasMore(hasMore)
                this.props.storeArticles(articles)
                this.setState({
                    loading:false
                })
            }
           
        });
    }
    loadMore=()=> {
        let {page,hasMore} = this.props;
        let {loading} = this.state;
        if (hasMore&&!loading) {
            loadMore(50,()=> {
                page++
                this.props.storePage(page)
                this.getArticles()
            })
        }
    }
    render(){
        let {articles,categories,hasMore,type} = this.props;
        function checkTabActive(id){
            if(type==undefined){
                type = '';
            }
            return type == id?'tabLink active':'tabLink'
        }
        return (
            <MyLayout showBg={true}>
                <div className="container">
                    <div className="view home">
                        <Row gutter={16}>
                            <Col md={16} sm={16} xs={24}>
                                <div className="postListWrapper">
                                    <div className="tabCard">
                                        <ul className="tabList">
                                            <li className="tabItem">
                                                <Link href='/'>
                                                    <a className={checkTabActive('')}>推荐</a>
                                                </Link>
                                            </li>
                                            <li className="tabItem">
                                                <Link href={`/?type=good`}>
                                                    <a className={checkTabActive('good')}>精华</a>
                                                </Link>
                                            </li>
                                            {
                                                categories.map((item, index) => {
                                                    return (
                                                        <li className="tabItem" key={item.key}>
                                                            <Link href={`/?type=${item.key}`}>
                                                                <a className={checkTabActive(item.key)}>{item.name}</a>
                                                            </Link>
                                                        </li>
                                                    )
                                                })
                                            }
                                        </ul>
                                    </div>
                                    <div className="post_list">
                                        { articles.map((item) => {
                                                return (
                                                    <ArticleItem item={item} key={item._id}></ArticleItem>
                                                )
                                            })
                                        }
                                    </div>
                                    <div style={{padding:'10px 20px'}}>
                                        <Skeleton loading={this.state.loading} active>
                                            <div></div>
                                        </Skeleton>
                                    </div>
                                    {/* <div style={{textAlign: 'center',height:'30px',marginTop:'30px' }}>
                                        <Spin indicator={<Icon type="loading" style={{ fontSize: 24 }} spin />} tip="卖力的加载中..." spinning={this.state.loading} size="large"/>
                                    </div> */}
                                    <p className="nomore" >{!hasMore?'已经全部加载完成了呢^_^':''}</p>
                                </div>
                            </Col>
                        </Row>    
                    </div>    
                </div>
            </MyLayout>
        )
    }
    

}


